import React, {useCallback, useEffect, useState} from 'react';
import {Layout, Menu, Row, Col, Modal, Tabs, Button} from 'antd';
import {Route} from 'react-router-dom';
import {push, replace} from 'react-router-redux';
import {connect} from 'react-redux';
import Admin from "./main/Admin";
import utils from '../utils/utils';
import {config} from "../config";
import {url} from "../config";
import Role from "./main/Role";

// 厂家管理
import ManufactorList from "./main/manufactor/ManufactorList";
import Classification from "./main/manufactor/Classification";
import Logs from "./main/manufactor/Logs";

// 经销商管理
import DistributorList from "./main/distributor/DistributorList";

//广告管理
import AdvertisingRanking from "./main/userAdvertising/AdvertisingRanking";

// 消费付费设置
import News from "./main/news/News";
import Carousel from "./main/carousel/Carousel";
import Notice from "./main/notice/Notice";
import NeedAgreement from "./main/agreement/NeedAgreement";
import SupplyAgreement from "./main/agreement/SupplyAgreement";
import Proposal from "./main/proposal/Proposal";
import ServiceModal from "../compoments/ServiceModal";
import MessageManager from "./main/message/MessageManager";
import Help from "./main/help/Help";
import AddDistributor from "./main/distributor/AddDistributor";
import AddManufactor from "./main/manufactor/AddManufactor";
import {UserOutlined, PoweroffOutlined} from "@ant-design/icons";
import UpdateManufactor from "./main/manufactor/UpdateManufactor";
import UpdateDistributor from "./main/distributor/UpdateDistributor";

const {SubMenu, Item: MenuItem} = Menu;
const {Sider, Header, Content} = Layout;
const {TabPane} = Tabs;

const IndexMain = (props) => {

    const [selectedMenu, setMenu] = useState('/main/message');
    const [serviceVisible, setServiceVisible] = useState(false);
    const [openKeys, setOpenKeys] = useState(['1', '2', '3', '4', '5', '6']);
    const [panes, setPanes] = useState([{
        path: '/main/message', title: '消息管理'
    }]);
    const [pageList, setPageList] = useState([]);
    const {userInfo = {}, popUp} = props;
    const permissionids = utils.getData('permissionids'); //获取权限id
    const adminName = utils.getData('admin_nickname');
// 主页的菜单
    const menuList = [
        {
            title: '消息管理', path: '1', 
            subMenu: [
                {title: '消息管理', path: '/main/message', page: MessageManager},
                {title: '广告管理', path: '/main/advertising/ranking', page: AdvertisingRanking},
                {title: '投诉与建议', path: '/main/proposal', page: Proposal}
            ]
        },
        {
            title: '厂家管理', path: '2', 
            subMenu: [
                {title: '厂家列表', path: '/main/factoryList', page: ManufactorList},
                {title: '新增厂家', path: '/main/addFactory', page: AddManufactor, hidden:!(permissionids.indexOf('2021020101') !== -1)},
                {title: '编辑厂家', path: '/main/updateFactory', page: UpdateManufactor, hidden: true},
            ]
        },
        {
            title: '经销商管理', path: '3', 
            subMenu: [
                {title: '经销商列表', path: '/main/distributor', page: DistributorList},
                {title: '新增经销商', path: '/main/addDistributor', page: AddDistributor},
                {title: '编辑经销商', path: '/main/updateDistributor', page: UpdateDistributor, hidden: true},
            ]
        },
        {
            title: '基础设置', path: '4', 
            subMenu: [
                {title: '客服设置', path: '/main/service', click: () => handleSetService()},
                {title: '付费设置', path: '/main/news', page: News},
                {title: '轮播图管理', path: '/main/carousel', page: Carousel},
                {title: '分类管理', path: '/main/types', page: Classification},
                {title: '公告管理', path: '/main/notice', page: Notice},
                {title: '帮助中心', path: '/main/help', page: Help},
            ]
        },
        {
            title: '协议管理', path: '5', 
            subMenu: [
                {title: '发布需求协议', path: '/main/needAgreement', page: NeedAgreement},
                {title: '发布供货协议', path: '/main/supplyAgreement', page: SupplyAgreement},
            ]
        },
        {
            title: '权限管理', path: '6', 
            subMenu: [
                {title: '管理员管理', path: '/main/admin', page: Admin,hidden:!(permissionids.indexOf('20210101') !== -1)},
                {title: '权限管理', path: '/main/role', page: Role,hidden:!(permissionids.indexOf('20210102') !== -1)},
                {title: '操作日志', path: '/main/log', page: Logs,hidden:!(permissionids.indexOf('20210103') !== -1)},
            ],hidden:!(permissionids.indexOf('202101') !== -1)
        },
    ];
    const onResize = useCallback(() => {
        props.setAppState({
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight,
            mobileModel: document.documentElement.clientWidth <= 768,
        });
    }, []);

    useEffect(() => {
        window.addEventListener('resize', onResize);
        window.reloadUser = () => {
            reloadUser();
        };
        const pageList = [];
        const pushList = (list) => {
            list.forEach((item) => {
                if (item.subMenu) {
                    pushList(item.subMenu);
                } else {
                    pageList.push(item);
                }
            });
        };
        pushList(menuList);
        setPageList(pageList);
        const panes = utils.getData('panes');
        if (panes) {
            setPanes(panes);
        }
        const selectedMenu = utils.getData('selectedMenu');
        if (selectedMenu) {
            setMenu(selectedMenu);
            props.setLocation(config.path + selectedMenu);
        }
        const openKeys = utils.getData('openKeys');
        if (openKeys) {
            setOpenKeys(openKeys);
        }
        return (() => {
            window.removeEventListener('resize', onResize);
        });
    }, []);

    useEffect(() => {
        utils.setData('openKeys', openKeys);
        utils.setData('selectedMenu', selectedMenu);
        utils.setData('panes', panes);
        window.closeWin = () => {
            closeWin(selectedMenu, panes);
        };
        window.onSelectWin = (data) => {
            onSelectMenu(null, data);
        };
        window.loginOut = () => {
            loginOut();
        };
    }, [openKeys, selectedMenu, panes]);

    const closeWin = (menu, panes) => {
        deleteTabs(menu, 'remove', panes);
    };

    const handleSetService = () => {
        setServiceVisible(true);
    };
    
    const createMenu = (menuList) => {
        return menuList.map(item => {
            if (item.subMenu && item.subMenu.length > 0) {
                const classname = (openKeys.findIndex((key) => key === item.path) !== -1) ? 'sider-sub-ul' : '';
                if (item.hidden) {
                    return;
                }
                return (
                    <SubMenu key={config.path + item.path}
                             className={'sider-sub ' + classname}
                             title={<span>{item.title}</span>}>
                        {
                            item.subMenu.map((sItem, index) => {
                                let style = {width: '50%'};
                                if (index % 2 !== 0) {
                                    style = {width: '40%'};
                                }
                                if (sItem.hidden) {
                                    return;
                                }
                                return (
                                    <MenuItem
                                        style={style}
                                        data={sItem}
                                        className={'sider-sub-menu main-color'}
                                        key={config.path + sItem.path}
                                    >
                                        <span>{sItem.title}</span>
                                    </MenuItem>
                                );
                            })
                        }
                    </SubMenu>
                );
            } else {
                if (item.path === '/main/welcome' && props.mobileModel) {
                    // 手机模式下，不显示操作指南
                } else {
                    return (
                        <MenuItem key={config.path + item.path} className='main-color'>
                            <span className="nav-text">{item.title}</span>
                        </MenuItem>
                    );
                }
            }
        });
    };

    const createMenuRoute = (menuList) => {
        return menuList.map((item, index) => {
            if (item.subMenu && item.subMenu.length > 0) {
                return createMenuRoute(item.subMenu);
            } else {
                return (
                    <Route key={config.path + item.path} exact={true} path={config.path + item.path}
                           component={item.page}/>
                );
            }
        });
    };

    const handleSetItem = (path) => {
        const index = pageList.findIndex((item) => item.path === path);
        return pageList[index].page;
    };

    const loginOut = () => {
        utils.signOut();
        props.setLocation("/");
    };

    const signOut = () => {
        Modal.confirm(
            {
                okText: '确定',
                cancelText: '取消',
                content: '退出登录',
                onOk() {
                    loginOut();
                },
                onCancel() {
                },
            });
    };

    const reloadUser = async () => {
        // const {code, data} = await ajax.post(url.getUserInfo);
        // if (code === 1) {
        //     props.setAppState({userInfo: {}});
        //     utils.setData('userInfo', JSON.stringify({}));
        // }
    };
    const onOpenChange = keys => {
        setOpenKeys(keys);
    };

    const onSelectMenu = (e, add) => {
        const key = add ? add.path : e.key;
        // 手机模式下，自动收菜单
        if (props.mobileModel) {
            props.setAppState({isMenuOpen: !props.isMenuOpen});
        }
        const index = panes.findIndex((item) => item.path === key);
        if (index === -1) {
            let data;
            if (add) {
                data = Object.assign({}, add);
            } else {
                data = Object.assign({}, e.item.props.data);
            }
            if (data.page) {
                delete data.page;
                panes.push(data);
                setPanes(Object.assign([], panes));
            } else {
                data.click();
                return;
            }
        } else {
            if (add && add.data) {
                const data = Object.assign({}, add);
                delete data.page;
                panes[index] = data;
                setPanes(Object.assign([], panes));
            }
        }
        if (add && add.data) {
            props.setLocation(key, add.data);
        } else {
            props.setLocation(key);
        }
        setMenu(key);
    };

    const handleChangeMenu = key => {
        const data = panes.filter((item) => item.path === key)[0];
        if (data && data.data) {
            props.setLocation(key, data.data);
        } else {
            props.setLocation(key);
        }
        setMenu(key);
    };

    const deleteTabs = (targetKey, action, list) => {
        const data = (list || panes);
        if (action === 'remove') {
            const index = data.findIndex((item) => item.path === targetKey);
            if (index !== -1) {
                data.splice(index, 1);
                setPanes(Object.assign([], data));
                if (data.length > index) {
                    handleChangeMenu(data[index].path);
                } else if (data.length > 0) {
                    handleChangeMenu(data[panes.length - 1].path);
                } else {
                    handleChangeMenu('/main');
                }
            }
        }
    };
    
    return (
        <Layout style={{height: '100%'}} className={'hiddenScroll'}>
            <Header className="main-header button-background">
                <Row>
                    <Col span={18}>
                        <img style={{margin: '0 15px 5px 15px'}} src={require('../img/logo.png')} className={'logo'}
                             alt=""/>
                        <span style={{fontSize: 30, fontWeight: 'bold'}}>{config.name}</span>
                    </Col>
                    <Col span={6}>
                        <div style={{float: 'right'}}>
                            <span> 您好，<UserOutlined style={{fontSize: 30}}/>{adminName}，欢迎使用</span>
                            <Button style={{background: 'rgb(13, 168, 222)', color: '#fff', marginLeft: 15}}
                                    onClick={() => signOut()}><PoweroffOutlined/>注销</Button>
                        </div>
                    </Col>
                </Row>
            </Header>
            <Layout>
                <Sider
                    width={280}
                    breakpoint="lg"
                    collapsedWidth="0"
                    collapsible
                    collapsed={props.isMenuOpen}
                    onBreakpoint={broken => {
                        //console.log(broken);
                    }}
                    onCollapse={() => {
                        props.setAppState({isMenuOpen: !props.isMenuOpen});
                    }}
                    trigger={null}
                    style={{
                        boxShadow: '2px 0 6px rgba(0, 21, 41, 0.35)',
                        overflowY: 'auto',
                        overflowX: 'hidden',
                        height: '100vh',
                        zIndex: 4,
                        position: props.mobileModel ? 'fixed' : 'relative',
                        background: '#28B6EE',
                    }}
                    className={'myScroll'}
                >
                    <Menu mode="inline"
                          openKeys={openKeys}
                          style={{background: '#28B6EE'}}
                          selectedKeys={[config.path + selectedMenu]}
                          onOpenChange={onOpenChange}
                          onClick={onSelectMenu}
                    >
                        {createMenu(menuList)}
                    </Menu>
                </Sider>
                <Layout style={{height: '100%', position: 'relative', overflow: 'hidden', background: '#fff'}}>
                    <Content className={'myScroll'} style={{overflowY: 'auto', padding: 15}}>
                        <Tabs
                            hideAdd
                            onChange={handleChangeMenu}
                            onEdit={deleteTabs}
                            className={'content-tabs'}
                            activeKey={config.path + selectedMenu}
                            type="editable-card"
                        >
                            {panes.map(pane => (
                                <TabPane
                                    className={'content-tabs-pane'} tab={pane.title} key={pane.path}
                                >
                                    {
                                        pageList.length &&
                                        <Route key={config.path + pane.path} exact={true} path={config.path + pane.path}
                                               component={handleSetItem(pane.path)}/>
                                    }
                                </TabPane>
                            ))}
                        </Tabs>
                    </Content>

                    {/*{createMenuRoute(menuList)}*/}
                </Layout>
            </Layout>
            <ServiceModal setVisible={setServiceVisible} visible={serviceVisible}/>
        </Layout>
    );
};

const mapStateToProps = (state) => {
    return {
        ...state.appReducer, // 全局的reducers
    };
};

const mapDispatchToProps = (dispatch) => ({
    // 跳转页面
    setLocation(path, data = {}) {
        dispatch(push(config.path + path, data));
    },
    // 设置全局的state
    setAppState(state) {
        dispatch({type: 'setAppState', state: state});
    },
    replaceLocation(path, data = {}) {
        dispatch(replace(config.path + path, data));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(IndexMain);
